package nz;

import javax.swing.*;
import java.awt.*;
import java.util.Map;
import java.util.Iterator;

public class PieChartPanel extends JPanel {
    private final Map<String, Integer> data;
    private final String title;
    private final Color[] colors = {
            Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.CYAN, Color.MAGENTA,
            Color.PINK, Color.YELLOW
    };
    private Iterator<Color> colorIterator;

    public PieChartPanel(Map<String, Integer> data, String title) {
        this.data = data;
        this.title = title;
        this.colorIterator = java.util.Arrays.stream(colors).iterator();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        int total = data.values().stream().mapToInt(Integer::intValue).sum();
        int startAngle = 0;

        int x = getWidth() / 4;
        int y = getHeight() / 4;
        int width = getWidth() / 2;
        int height = getHeight() / 2;

        g2d.setFont(new Font("微软雅黑", Font.BOLD, 16));
        g2d.drawString(title, getWidth() / 2 - g2d.getFontMetrics().stringWidth(title) / 2, 20);

        for (Map.Entry<String, Integer> entry : data.entrySet()) {
            int arcAngle = (int) Math.round(360.0 * entry.getValue() / total);

            // 获取下一个颜色并设置
            g2d.setColor(getNextColor());
            g2d.fillArc(x, y, width, height, startAngle, arcAngle);

            int midAngle = startAngle + arcAngle / 2;
            double radian = Math.toRadians(midAngle);

            // 计算百分比并将其绘制在扇形中心
            double percentage = (double) entry.getValue() / total * 100;
            String percentageText = String.format("%.1f%%", percentage); // 保留一位小数

            int percentageLabelX = (int) (x + width / 2 + (width / 4) * Math.cos(radian));
            int percentageLabelY = (int) (y + height / 2 - (height / 4) * Math.sin(radian));

            // 设置颜色为黑色，确保百分比在扇形中清晰可见
            g2d.setColor(Color.BLACK);
            g2d.drawString(percentageText, percentageLabelX, percentageLabelY);

            // 绘制类别名称在扇形外部
            int labelX = (int) (x + width / 2 + (width / 2 + 20) * Math.cos(radian));
            int labelY = (int) (y + height / 2 - (height / 2 + 20) * Math.sin(radian));

            // 设置颜色为黑色
            g2d.setColor(Color.BLACK);
            g2d.drawString(entry.getKey(), labelX, labelY);

            startAngle += arcAngle;
        }
    }

    // 从颜色数组中循环获取下一个颜色
    private Color getNextColor() {
        if (!colorIterator.hasNext()) {
            colorIterator = java.util.Arrays.stream(colors).iterator(); // 如果颜色用尽，重新开始
        }
        return colorIterator.next();
    }
}
